import {login, logout, getInfo} from '@/api/user'
import storage from '@/util/storage'
import localStorage from '@/util/localStorage'

const user = {
    state: {
        username: '',
        nickname: '',
        token: '',

        roles: [],
        permissions: []
    },
    getters: {
        isLogin(state) {
            return state.username !== "" && state.token !== ""
        },
        permission(state){
            return state.permissions
        },
        role(state){
            return state.roles
        }
    },
    mutations: {
        SAVE_USERNAME(state, username) {

            state.username = username;
        },
        SAVE_NICKNAME(state, nickname) {
            state.nickname = nickname;
        },
        SAVE_TOKEN(state, token) {
            state.token = token;
        },
        SAVE_ROLES(state, roles){
            state.roles=roles;
        },
        SAVE_PERMISSIONS(state, permissions){
            state.permissions=permissions;
        }

},
actions: {
    LOGIN({commit}, user)
    {
        return new Promise(function (resolve) {
            login(user).then(res => {
                console.log("store-res:" + res)
                //这里需要将获取的数据保存起来
                commit("SAVE_USERNAME", res.data.liuUser.userName);
                commit("SAVE_NICKNAME", res.data.liuUser.nickName);


                commit("SAVE_TOKEN", res.data.token);
                storage.saveSessionObject("loginUser", res.data)
                localStorage.saveLocalStorageObject("loginUser", res.data)
                resolve(res)
            })
        });

    }
,
    GET_INFO({commit})
    {
        return new Promise(resolve => {
            getInfo().then(res => {
                console.log("这里是前端鉴权获取的res" + res);
                commit("SAVE_ROLES",res.data.roles);
                commit("SAVE_PERMISSIONS",res.data.perms) ;
                resolve()
            })
        })

    }
,
    LOGOUT({commit})
    {
        return new Promise(function (resolve) {
            logout().then(res => {
                console.log(res)
                //这里需要将获取的数据保存起来
                commit("SAVE_USERNAME");
                commit("SAVE_NICKNAME");
                commit("SAVE_TOKEN");
                storage.remove("loginUser")
                localStorage.remove("loginUser")
                resolve(res.data)
            })
        });

    }
,
    RECOVERY_USER({commit})
    {
        //先从session中获取
        let loginUser = storage.getSessionObject(`loginUser`);
        if (loginUser) {
            commit("SAVE_USERNAME", loginUser.liuUser.userName);
            commit("SAVE_NICKNAME", loginUser.liuUser.nickName);
            commit("SAVE_TOKEN", loginUser.token);
        }
    }
}
}
export default user